<template>
  <div class="property-editor">
    <el-tabs v-model="activeTab" class="property-tabs">
      <!-- 基础属性 -->
      <el-tab-pane label="基础属性" name="basic">
        <div class="property-section">
          <el-form label-width="90px" size="small">
            <el-form-item label="字段名">
              <el-input v-model="localComponent.field" placeholder="field_name" />
            </el-form-item>
            
            <el-form-item label="字段标签">
              <el-input v-model="localComponent.label" placeholder="标签文本" />
            </el-form-item>
            
            <el-form-item label="占位提示">
              <el-input v-model="localComponent.placeholder" placeholder="请输入..." />
            </el-form-item>
            
            <el-form-item label="默认值">
              <component 
                :is="getValueInputComponent()"
                v-model="localComponent.defaultValue"
                :placeholder="getDefaultValuePlaceholder()"
                style="width: 100%"
              />
            </el-form-item>
            
            <el-form-item label="必填">
              <el-switch v-model="localComponent.required" />
            </el-form-item>
            
            <el-form-item label="禁用">
              <el-switch v-model="localComponent.disabled" />
            </el-form-item>
            
            <el-form-item label="隐藏">
              <el-switch v-model="localComponent.hidden" />
            </el-form-item>
            
            <el-form-item label="只读">
              <el-switch v-model="localComponent.readonly" />
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 高级属性 -->
      <el-tab-pane label="高级属性" name="advanced">
        <div class="property-section">
          <el-form label-width="90px" size="small">
            <!-- 尺寸 -->
            <el-form-item label="尺寸">
              <el-select v-model="localComponent.size" placeholder="选择尺寸">
                <el-option label="大" value="large" />
                <el-option label="默认" value="default" />
                <el-option label="小" value="small" />
              </el-select>
            </el-form-item>

            <!-- 宽度 -->
            <el-form-item label="宽度">
              <el-input v-model="localComponent.width" placeholder="如：100% 或 200px">
                <template #append>
                  <el-select v-model="widthUnit" style="width: 80px">
                    <el-option label="%" value="%" />
                    <el-option label="px" value="px" />
                  </el-select>
                </template>
              </el-input>
            </el-form-item>

            <!-- 对齐方式 -->
            <el-form-item label="对齐">
              <el-radio-group v-model="localComponent.align">
                <el-radio-button label="left">左对齐</el-radio-button>
                <el-radio-button label="center">居中</el-radio-button>
                <el-radio-button label="right">右对齐</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <!-- 自定义class -->
            <el-form-item label="CSS类">
              <el-input v-model="localComponent.customClass" placeholder="custom-class" />
            </el-form-item>

            <!-- 帮助文本 -->
            <el-form-item label="帮助文本">
              <el-input 
                v-model="localComponent.helpText" 
                type="textarea"
                :rows="2"
                placeholder="字段说明或提示信息"
              />
            </el-form-item>

            <!-- 前缀图标 -->
            <el-form-item label="前缀图标">
              <el-input v-model="localComponent.prefixIcon" placeholder="Search">
                <template #append>
                  <el-button @click="showIconPicker = true">选择</el-button>
                </template>
              </el-input>
            </el-form-item>

            <!-- 后缀图标 -->
            <el-form-item label="后缀图标">
              <el-input v-model="localComponent.suffixIcon" placeholder="View">
                <template #append>
                  <el-button @click="showIconPicker = true">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 校验规则 -->
      <el-tab-pane label="校验规则" name="validation">
        <div class="property-section">
          <div class="validation-header">
            <span>校验规则列表</span>
            <el-button type="primary" size="small" @click="addValidationRule">
              <el-icon><Plus /></el-icon>
              添加规则
            </el-button>
          </div>

          <div v-if="validationRules.length === 0" class="empty-validation">
            <el-empty description="暂无校验规则" :image-size="80" />
          </div>

          <div v-else class="validation-list">
            <el-card 
              v-for="(rule, index) in validationRules" 
              :key="index"
              class="validation-item"
              shadow="never"
            >
              <div class="validation-item-header">
                <el-tag :type="getValidationTypeColor(rule.type)" size="small">
                  {{ getValidationTypeName(rule.type) }}
                </el-tag>
                <el-button 
                  type="danger" 
                  size="small" 
                  text 
                  @click="removeValidationRule(index)"
                >
                  删除
                </el-button>
              </div>

              <el-form label-width="80px" size="small" style="margin-top: 10px">
                <el-form-item label="规则类型">
                  <el-select v-model="rule.type" @change="onValidationTypeChange(rule)">
                    <el-option label="必填" value="required" />
                    <el-option label="最小长度" value="minLength" />
                    <el-option label="最大长度" value="maxLength" />
                    <el-option label="正则表达式" value="pattern" />
                    <el-option label="邮箱" value="email" />
                    <el-option label="手机号" value="phone" />
                    <el-option label="网址" value="url" />
                    <el-option label="数字" value="number" />
                    <el-option label="整数" value="integer" />
                    <el-option label="自定义" value="custom" />
                  </el-select>
                </el-form-item>

                <el-form-item v-if="rule.type === 'minLength'" label="最小长度">
                  <el-input-number v-model="rule.value" :min="1" />
                </el-form-item>

                <el-form-item v-if="rule.type === 'maxLength'" label="最大长度">
                  <el-input-number v-model="rule.value" :min="1" />
                </el-form-item>

                <el-form-item v-if="rule.type === 'pattern'" label="正则表达式">
                  <el-input v-model="rule.value" placeholder="如：^[0-9]+$" />
                </el-form-item>

                <el-form-item v-if="rule.type === 'custom'" label="自定义函数">
                  <el-input 
                    v-model="rule.validator" 
                    type="textarea"
                    :rows="3"
                    placeholder="function(rule, value, callback) { ... }"
                  />
                </el-form-item>

                <el-form-item label="错误提示">
                  <el-input v-model="rule.message" placeholder="请输入错误提示信息" />
                </el-form-item>

                <el-form-item label="触发方式">
                  <el-select v-model="rule.trigger">
                    <el-option label="失焦时" value="blur" />
                    <el-option label="输入时" value="change" />
                    <el-option label="两者" value="blur,change" />
                  </el-select>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </div>
      </el-tab-pane>

      <!-- 数据联动 -->
      <el-tab-pane label="数据联动" name="linkage">
        <div class="property-section">
          <el-alert 
            title="数据联动说明" 
            type="info" 
            :closable="false"
            style="margin-bottom: 15px"
          >
            设置字段之间的联动关系，当某个字段值变化时，自动更新其他字段
          </el-alert>

          <div class="linkage-header">
            <span>联动规则列表</span>
            <el-button type="primary" size="small" @click="addLinkageRule">
              <el-icon><Plus /></el-icon>
              添加联动
            </el-button>
          </div>

          <div v-if="linkageRules.length === 0" class="empty-linkage">
            <el-empty description="暂无联动规则" :image-size="80" />
          </div>

          <div v-else class="linkage-list">
            <el-card 
              v-for="(rule, index) in linkageRules" 
              :key="index"
              class="linkage-item"
              shadow="never"
            >
              <div class="linkage-item-header">
                <span class="linkage-title">联动规则 {{ index + 1 }}</span>
                <el-button 
                  type="danger" 
                  size="small" 
                  text 
                  @click="removeLinkageRule(index)"
                >
                  删除
                </el-button>
              </div>

              <el-form label-width="80px" size="small" style="margin-top: 10px">
                <el-form-item label="触发字段">
                  <el-select v-model="rule.sourceField" placeholder="选择字段">
                    <el-option 
                      v-for="field in availableFields" 
                      :key="field.field"
                      :label="field.label"
                      :value="field.field"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="触发条件">
                  <el-select v-model="rule.condition">
                    <el-option label="等于" value="equals" />
                    <el-option label="不等于" value="notEquals" />
                    <el-option label="包含" value="contains" />
                    <el-option label="不包含" value="notContains" />
                    <el-option label="大于" value="greaterThan" />
                    <el-option label="小于" value="lessThan" />
                    <el-option label="为空" value="isEmpty" />
                    <el-option label="不为空" value="isNotEmpty" />
                  </el-select>
                </el-form-item>

                <el-form-item v-if="!['isEmpty', 'isNotEmpty'].includes(rule.condition)" label="比较值">
                  <el-input v-model="rule.compareValue" placeholder="输入比较值" />
                </el-form-item>

                <el-form-item label="目标字段">
                  <el-select v-model="rule.targetField" placeholder="选择字段">
                    <el-option 
                      v-for="field in availableFields" 
                      :key="field.field"
                      :label="field.label"
                      :value="field.field"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="联动动作">
                  <el-select v-model="rule.action">
                    <el-option label="设置值" value="setValue" />
                    <el-option label="显示" value="show" />
                    <el-option label="隐藏" value="hide" />
                    <el-option label="启用" value="enable" />
                    <el-option label="禁用" value="disable" />
                    <el-option label="必填" value="require" />
                    <el-option label="非必填" value="unrequire" />
                  </el-select>
                </el-form-item>

                <el-form-item v-if="rule.action === 'setValue'" label="设置的值">
                  <el-input v-model="rule.value" placeholder="输入要设置的值" />
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </div>
      </el-tab-pane>

      <!-- 表达式绑定 -->
      <el-tab-pane label="表达式" name="expression">
        <div class="property-section">
          <el-alert 
            title="表达式说明" 
            type="info" 
            :closable="false"
            style="margin-bottom: 15px"
          >
            <div>使用JavaScript表达式动态计算字段值</div>
            <div style="margin-top: 5px; font-size: 12px">
              可用变量：form（表单数据）、field（当前字段）、utils（工具函数）
            </div>
          </el-alert>

          <el-form label-width="90px" size="small">
            <el-form-item label="默认值表达式">
              <el-input 
                v-model="expressions.defaultValue"
                type="textarea"
                :rows="3"
                placeholder="如：form.price * form.quantity"
              />
            </el-form-item>

            <el-form-item label="显示条件">
              <el-input 
                v-model="expressions.visible"
                type="textarea"
                :rows="2"
                placeholder="如：form.type === 'custom'"
              />
            </el-form-item>

            <el-form-item label="禁用条件">
              <el-input 
                v-model="expressions.disabled"
                type="textarea"
                :rows="2"
                placeholder="如：form.status === 'locked'"
              />
            </el-form-item>

            <el-form-item label="必填条件">
              <el-input 
                v-model="expressions.required"
                type="textarea"
                :rows="2"
                placeholder="如：form.amount > 1000"
              />
            </el-form-item>

            <el-form-item label="选项数据源">
              <el-input 
                v-model="expressions.options"
                type="textarea"
                :rows="3"
                placeholder="如：api.getDepartments()"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="testExpression">
                <el-icon><View /></el-icon>
                测试表达式
              </el-button>
              <el-button @click="clearExpressions">
                清空所有表达式
              </el-button>
            </el-form-item>
          </el-form>

          <el-divider content-position="left">表达式示例</el-divider>
          <div class="expression-examples">
            <div class="example-item">
              <div class="example-title">计算总价</div>
              <code>form.price * form.quantity</code>
            </div>
            <div class="example-item">
              <div class="example-title">条件显示</div>
              <code>form.type === 'vip'</code>
            </div>
            <div class="example-item">
              <div class="example-title">日期格式化</div>
              <code>utils.formatDate(form.date, 'YYYY-MM-DD')</code>
            </div>
            <div class="example-item">
              <div class="example-title">数据转换</div>
              <code>form.list.map(item => item.name).join(',')</code>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, View } from '@element-plus/icons-vue'

const props = defineProps({
  component: {
    type: Object,
    required: true
  },
  allComponents: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:component'])

const activeTab = ref('basic')
const widthUnit = ref('%')
const showIconPicker = ref(false)

// 本地组件数据
const localComponent = reactive({ ...props.component })

// 校验规则
const validationRules = ref([])

// 联动规则
const linkageRules = ref([])

// 表达式
const expressions = reactive({
  defaultValue: '',
  visible: '',
  disabled: '',
  required: '',
  options: ''
})

// 可用字段列表
const availableFields = computed(() => {
  return props.allComponents.filter(c => c.field !== props.component.field)
})

// 监听组件变化
watch(() => props.component, (newVal) => {
  Object.assign(localComponent, newVal)
  // 加载已有的规则
  validationRules.value = newVal.validationRules || []
  linkageRules.value = newVal.linkageRules || []
  Object.assign(expressions, newVal.expressions || {})
}, { deep: true })

// 监听本地组件变化，同步给父组件
watch(localComponent, (newVal) => {
  emit('update:component', {
    ...newVal,
    validationRules: validationRules.value,
    linkageRules: linkageRules.value,
    expressions: { ...expressions }
  })
}, { deep: true })

// 获取值输入组件
const getValueInputComponent = () => {
  const type = localComponent.type
  if (type === 'number') return 'el-input-number'
  if (type === 'switch') return 'el-switch'
  if (type === 'date') return 'el-date-picker'
  if (type === 'textarea') return 'el-input'
  return 'el-input'
}

// 获取默认值占位符
const getDefaultValuePlaceholder = () => {
  const type = localComponent.type
  if (type === 'number') return '输入数字'
  if (type === 'date') return '选择日期'
  return '输入默认值'
}

// 校验规则方法
const addValidationRule = () => {
  validationRules.value.push({
    type: 'required',
    message: '此字段为必填项',
    trigger: 'blur'
  })
}

const removeValidationRule = (index) => {
  validationRules.value.splice(index, 1)
}

const onValidationTypeChange = (rule) => {
  // 根据规则类型设置默认提示
  const messages = {
    required: '此字段为必填项',
    minLength: '长度不能少于指定字符',
    maxLength: '长度不能超过指定字符',
    pattern: '格式不正确',
    email: '请输入正确的邮箱地址',
    phone: '请输入正确的手机号',
    url: '请输入正确的网址',
    number: '请输入数字',
    integer: '请输入整数',
    custom: '自定义校验失败'
  }
  rule.message = messages[rule.type] || '校验失败'
}

const getValidationTypeName = (type) => {
  const names = {
    required: '必填',
    minLength: '最小长度',
    maxLength: '最大长度',
    pattern: '正则',
    email: '邮箱',
    phone: '手机号',
    url: '网址',
    number: '数字',
    integer: '整数',
    custom: '自定义'
  }
  return names[type] || type
}

const getValidationTypeColor = (type) => {
  if (type === 'required') return 'danger'
  if (type === 'custom') return 'warning'
  return 'info'
}

// 联动规则方法
const addLinkageRule = () => {
  linkageRules.value.push({
    sourceField: '',
    condition: 'equals',
    compareValue: '',
    targetField: '',
    action: 'show',
    value: ''
  })
}

const removeLinkageRule = (index) => {
  linkageRules.value.splice(index, 1)
}

// 表达式方法
const testExpression = () => {
  ElMessage.success('表达式测试通过！（实际使用时会进行真实校验）')
}

const clearExpressions = () => {
  expressions.defaultValue = ''
  expressions.visible = ''
  expressions.disabled = ''
  expressions.required = ''
  expressions.options = ''
  ElMessage.success('已清空所有表达式')
}
</script>

<style scoped>
.property-editor {
  height: 100%;
  overflow-y: auto;
}

.property-tabs {
  height: 100%;
}

.property-section {
  padding: 15px;
}

/* 校验规则 */
.validation-header,
.linkage-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-weight: 600;
  color: #303133;
}

.empty-validation,
.empty-linkage {
  padding: 30px 0;
}

.validation-list,
.linkage-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.validation-item,
.linkage-item {
  border: 1px solid #e4e7ed;
}

.validation-item-header,
.linkage-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.linkage-title {
  font-weight: 600;
  color: #303133;
}

/* 表达式示例 */
.expression-examples {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.example-item {
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.example-title {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.example-item code {
  font-size: 13px;
  color: #303133;
  font-family: 'Consolas', 'Monaco', monospace;
}

/* 滚动条样式 */
.property-editor::-webkit-scrollbar {
  width: 6px;
}

.property-editor::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.property-editor::-webkit-scrollbar-thumb:hover {
  background: #c0c4cc;
}
</style>

